/**
* 大潮提现链接分发 - 修复压缩数据版
* export DaChao="手机号1&密码1 手机号2&密码2"
* export QYWX_BASE_CONFIG="企业ID#Secret#AgentId#代理地址"
* export DC_separate="接收人ID1#手机号1#备注1\n接收人ID2#手机号2#备注2"
* export DC_Summary="接收人ID|手机号1#手机号2#手机号3"
*/
const $ = new Env('大潮提现链接分发')
const DaChao = ($.isNode() ? process.env.DaChao : $.getdata("DaChao")) || '';
const QYWX_BASE_CONFIG = ($.isNode() ? process.env.QYWX_BASE_CONFIG : $.getdata("QYWX_BASE_CONFIG")) || '';
const DC_separate = ($.isNode() ? process.env.DC_separate : $.getdata("DC_separate")) || '';
const DC_Summary = ($.isNode() ? process.env.DC_Summary : $.getdata("DC_Summary")) || '';

let allResults = [];
let receiverConfig = {};
let summaryReceivers = [];
let phoneRemarks = {};
let corpId = '', secret = '', agentId = '', proxyUrl = '';

// 使用Node.js内置模块
const crypto = require('crypto');
const zlib = require('zlib');

!(async () => {
    if (!DaChao) {
        console.log("⚠️ 请先设置环境变量 DaChao");
        return;
    }
    
    // 解析配置
    parseReceiverConfig();
    parseSummaryReceiverConfig();
    parseWechatBaseConfig();
    
    let accounts = DaChao.split(/\s+/).filter(item => item.includes('&'));
    
    for (const item of accounts) {
        if (!item.includes('&')) continue;
        
        const [phone, pwd] = item.split('&');
        const phone_number = phone.trim();
        const password = pwd.trim();
        const displayName = getDisplayName(phone_number);
        
        console.log(`\n----------- 🍺 账号【${accounts.indexOf(item) + 1}/${accounts.length}】 -----------`);
        console.log(`📱 【${displayName}】${phone_number}`);
        
        try {
            const result = await processAccount(phone_number, password, displayName);
            allResults.push(result);
            
            // 随机延迟
            await $.wait(Math.floor(Math.random() * 2000) + 1000);
        } catch (e) {
            console.log(`❌ 处理账号时出错: ${e.message}`);
            allResults.push({
                phone: phone_number,
                displayName: displayName,
                success: false,
                message: `❌ 处理出错: ${e.message}`,
                redPackets: [],
                totalAmount: 0
            });
        }
    }
    
    console.log('\n----------- 🎊 执行结束 🎊 -----------');
    await sendNotifications();
})().catch((e) => {
    console.log(e);
}).finally(() => {
    $.done({});
});

// 处理压缩数据
function handleCompressedData(data, encoding) {
    if (!data) return null;
    
    try {
        // 如果是Buffer数据，尝试解压
        if (Buffer.isBuffer(data)) {
            // 检查是否是gzip压缩数据
            if (data[0] === 0x1f && data[1] === 0x8b) {
                try {
                    const decompressed = zlib.gunzipSync(data);
                    return decompressed.toString('utf8');
                } catch (e) {
                    console.log('gzip解压失败，尝试原始数据');
                }
            }
            // 直接转换为字符串
            return data.toString('utf8');
        }
        
        // 如果是字符串，直接返回
        if (typeof data === 'string') {
            return data;
        }
        
        // 其他情况转换为字符串
        return String(data);
    } catch (e) {
        console.log(`处理响应数据失败: ${e.message}`);
        return data;
    }
}

// 完整处理账号逻辑
async function processAccount(phone, password, displayName) {
    let sessionId = '';
    let accountId = '';
    
    try {
        console.log("1️⃣ 初始化会话...");
        const initSession = await commonPost('/api/account/init', '');
        if (!initSession || !initSession.data || !initSession.data.session) {
            throw new Error("初始化会话失败");
        }
        sessionId = initSession.data.session.id;
        console.log("✅ 初始化会话成功");
        
        console.log("2️⃣ 获取签名密钥...");
        const init = await initGet(`/web/init?client_id=10048`);
        if (!init || !init.data || !init.data.client || !init.data.client.signature_key) {
            throw new Error("获取签名密钥失败");
        }
        const signature_key = init.data.client.signature_key;
        console.log("✅ 获取签名密钥成功");
        
        console.log("3️⃣ 账号密码认证...");
        const credential_auth = await passportPost('/web/oauth/credential_auth', phone, password, signature_key);
        if (!credential_auth || !credential_auth.data) {
            throw new Error("认证失败");
        }
        const code = credential_auth.data.authorization_code.code;
        console.log("✅ 认证成功，获取授权码");
        
        console.log("4️⃣ 登录账号...");
        const login = await commonPost('/api/zbtxz/login', `check_token=&code=${code}&token=&type=-1&union_id=`, sessionId);
        if (!login || !login.data || !login.data.session) {
            throw new Error("登录失败");
        }
        accountId = login.data.session.account_id;
        sessionId = login.data.session.id;
        console.log(`✅ 登录成功, account_id: ${accountId}`);
        
        console.log("5️⃣ 获取账户详情...");
        const detail = await commonGet('/api/user_mumber/account_detail', sessionId, accountId);
        if (!detail || !detail.data || !detail.data.rst) {
            throw new Error("获取账户详情失败");
        }
        console.log(`✅ 获取账户详情成功, 昵称: ${detail.data.rst.nick_name}`);
        
        console.log("6️⃣ 获取活动签名...");
        const timestamp = Math.round(new Date().getTime()/1000).toString();
        const signatureData = {
            "accountId": accountId,
            "signature": crypto.createHash('sha256').update(` &id&mobile&nick_name&&${timestamp}&&KO>N<O5&3^L1%23YH0H1#G91*2H`).digest('hex'),
            "mobile": "1",
            "sessionId": sessionId,
            "login": "1",
            "user": {
                "realName": "",
                "image_url": detail.data.rst.image_url,
                "nick_name": detail.data.rst.nick_name,
                "is_face_verify": 0,
                "idcard": "",
                "id": accountId
            },
            "timestamp": timestamp,
            "sign": "xsb_hn"
        };
        
        const signature = await activityPost('/memberhy/tm/signature', signatureData, sessionId, accountId);
        if (!signature || !signature.id) {
            throw new Error("获取签名失败");
        }
        console.log("✅ 获取活动签名成功");
        
        const member = JSON.stringify({
            "id": signature.id,
            "black": 0,
            "btoken": signature.btoken,
            "expire": signature.expire,
            "token": signature.token,
            "source": "xsb_hn",
            "mobile": signature.mobile,
            "mark": signature.mark,
            "mtoken": signature.mtoken,
            "stoken": signature.stoken,
            "nick_name": encodeURI(signature.nick_name),
            "avatar": signature.avatar
        });
        
        console.log("7️⃣ 获取红包信息...");
        const prizeInfo = await activityGet(`/lotteryhy/api/client/cj/member/prize/info?prize_type=3&page=1&count=20`, member, accountId);
        if (!prizeInfo || !prizeInfo.data || prizeInfo.data.length === 0) {
            return {
                phone: phone,
                displayName: displayName,
                success: true,
                message: "ℹ️ 未找到可提现的红包",
                redPackets: [],
                totalAmount: 0
            };
        }
        
        const redPackets = [];
        let totalAmount = 0;
        let hasPrize = false;
        
        for (let prize of prizeInfo.data) {
            if (prize.prize_type == 3 && prize.status != 2 && prize.status != 6) {
                let prizeInfoObj = JSON.parse(prize.prize_info);
                let code = prizeInfoObj.code;
                
                let amount = parseAmount(prize.prize_content);
                totalAmount += amount;
                
                let redPacket = {
                    content: prize.prize_content,
                    link: `https://m.aihoge.com/lottery/rotor/drawRedPacket?CHECK_CODE=${code}`,
                    code: code,
                    amount: amount
                };
                console.log(`📮 红包内容: ${prize.prize_content}`);
                console.log(`🔗 提现链接: ${redPacket.link}`);
                redPackets.push(redPacket);
                hasPrize = true;
            }
        }
        
        return {
            phone: phone,
            displayName: displayName,
            success: true,
            message: hasPrize ? `✅ 发现 ${redPackets.length} 个红包` : "ℹ️ 没有可提现的红包",
            redPackets: redPackets,
            totalAmount: totalAmount
        };
        
    } catch (e) {
        console.log(`❌ 处理过程中出错: ${e.message}`);
        return {
            phone: phone,
            displayName: displayName,
            success: false,
            message: `❌ 处理出错: ${e.message}`,
            redPackets: [],
            totalAmount: 0
        };
    }
}

// 解析红包金额
function parseAmount(content) {
    let match = content.match(/(\d+(\.\d+)?)/);
    if (match) {
        return parseFloat(match[0]);
    }
    return 0;
}

// RSA加密函数
function rsaEncrypt(publicKey, data) {
    try {
        const buffer = Buffer.from(data);
        const encrypted = crypto.publicEncrypt({
            key: publicKey,
            padding: crypto.constants.RSA_PKCS1_PADDING
        }, buffer);
        return encrypted.toString('base64');
    } catch (e) {
        console.log(`RSA加密失败: ${e.message}`);
        return data;
    }
}

// 生成UUID
function generateUUID() {
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
        const r = (Math.random() * 16) | 0;
        const v = c === 'x' ? r : (r & 0x3) | 0x8;
        return v.toString(16);
    });
}

// 初始化GET请求
async function initGet(url) {
    return new Promise(resolve => {
        const options = {
            url: `https://passport.tmuyun.com${url}`,
            headers: {
                'Connection': 'Keep-Alive',
                'Cache-Control': 'no-cache',
                'X-REQUEST-ID': generateUUID(),
                'user-agent': 'Android;11;10048;14.1.6;1.0;null;M2001J2E',
            },
            encoding: null // 获取原始Buffer数据
        };
        $.get(options, (err, resp, data) => {
            try {
                if (err) {
                    console.log(`请求失败: ${err}`);
                    resolve(null);
                } else {
                    // 处理可能的压缩数据
                    const processedData = handleCompressedData(data);
                    if (processedData) {
                        resolve(JSON.parse(processedData));
                    } else {
                        resolve(null);
                    }
                }
            } catch (e) {
                console.log(`解析响应失败: ${e}`);
                console.log(`原始数据: ${data ? data.toString('hex').substring(0, 100) : 'null'}`);
                resolve(null);
            }
        });
    });
}

// 认证POST请求
async function passportPost(url, phone, password, signature_key) {
    const uuid = generateUUID();
    const clientId = '10048';
    
    // RSA公钥
    const publicKey = `-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQD6XO7e9YeAOs+cFqwa7ETJ+WXi
zPqQeXv68i5vqw9pFREsrqiBTRcg7wB0RIp3rJkDpaeVJLsZqYm5TW7FWx/iOiXF
c+zCPvaKZric2dXCw27EvlH5rq+zwIPDAJHGAfnn1nmQH7wR3PCatEIb8pz5GFlT
HMlluw4ZYmnOwg+thwIDAQAB
-----END PUBLIC KEY-----`;
    
    // RSA加密密码
    const encryptedPassword = rsaEncrypt(publicKey, password);
    
    let body = `client_id=${clientId}&password=${encodeURIComponent(encryptedPassword)}&phone_number=${phone}`;
    const str = `post%%/web/oauth/credential_auth?${body}%%${uuid}%%`;
    
    // HMAC-SHA256签名
    const signature = crypto.createHmac('sha256', signature_key).update(str).digest('hex');
    
    return new Promise(resolve => {
        const options = {
            url: `https://passport.tmuyun.com${url}`,
            headers: {
                'Connection': 'Keep-Alive',
                'X-REQUEST-ID': uuid,
                'X-SIGNATURE': signature,
                'Cache-Control': 'no-cache',
                'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
                'user-agent': 'Android;11;10048;14.1.6;1.0;null;M2001J2E',
            },
            body: body,
            encoding: null
        };
        $.post(options, (err, resp, data) => {
            try {
                if (err) {
                    console.log(`请求失败: ${err}`);
                    resolve(null);
                } else {
                    const processedData = handleCompressedData(data);
                    if (processedData) {
                        resolve(JSON.parse(processedData));
                    } else {
                        resolve(null);
                    }
                }
            } catch (e) {
                console.log(`解析响应失败: ${e}`);
                resolve(null);
            }
        });
    });
}

// 通用GET请求
async function commonGet(url, sessionId, accountId) {
    const uuid = generateUUID();
    const time = Date.now();
    const signatureSalt = "FR*r!isE5W";
    const tenantId = '94';
    
    const str = `${url}&&${sessionId}&&${uuid}&&${time}&&${signatureSalt}&&${tenantId}`;
    const signature = crypto.createHash('sha256').update(str).digest('hex');
    
    return new Promise(resolve => {
        const options = {
            url: `https://vapp.tmuyun.com${url}`,
            headers: {
                'Connection': 'Keep-Alive',
                'X-TIMESTAMP': time,
                'X-SESSION-ID': sessionId,
                'X-REQUEST-ID': uuid,
                'X-SIGNATURE': signature,
                'X-TENANT-ID': tenantId,
                'X-ACCOUNT-ID': accountId,
                'Cache-Control': 'no-cache',
                'user-agent': '14.1.6;' + generateUUID() + ';Xiaomi M2001J2E;Android;11;6.11.0',
            },
            encoding: null
        };
        $.get(options, (err, resp, data) => {
            try {
                if (err) {
                    console.log(`请求失败: ${err}`);
                    resolve(null);
                } else {
                    const processedData = handleCompressedData(data);
                    if (processedData) {
                        resolve(JSON.parse(processedData));
                    } else {
                        resolve(null);
                    }
                }
            } catch (e) {
                console.log(`解析响应失败: ${e}`);
                resolve(null);
            }
        });
    });
}

// 通用POST请求
async function commonPost(url, body, sessionId = '', accountId = '') {
    const uuid = generateUUID();
    const time = Date.now();
    const signatureSalt = "FR*r!isE5W";
    const tenantId = '94';
    
    const str = `${url}&&${sessionId}&&${uuid}&&${time}&&${signatureSalt}&&${tenantId}`;
    const signature = crypto.createHash('sha256').update(str).digest('hex');
    
    return new Promise(resolve => {
        const options = {
            url: `https://vapp.tmuyun.com${url}`,
            headers: {
                'Connection': 'Keep-Alive',
                'X-TIMESTAMP': time,
                'X-SESSION-ID': sessionId,
                'X-REQUEST-ID': uuid,
                'X-SIGNATURE': signature,
                'X-TENANT-ID': tenantId,
                'X-ACCOUNT-ID': accountId,
                'Cache-Control': 'no-cache',
                'Content-Type': 'application/x-www-form-urlencoded',
                'user-agent': '14.1.6;' + generateUUID() + ';Xiaomi M2001J2E;Android;11;6.11.0',
            },
            body: body,
            encoding: null
        };
        $.post(options, (err, resp, data) => {
            try {
                if (err) {
                    console.log(`请求失败: ${err}`);
                    resolve(null);
                } else {
                    const processedData = handleCompressedData(data);
                    if (processedData) {
                        resolve(JSON.parse(processedData));
                    } else {
                        resolve(null);
                    }
                }
            } catch (e) {
                console.log(`解析响应失败: ${e}`);
                resolve(null);
            }
        });
    });
}

// 活动GET请求
async function activityGet(url, member, accountId) {
    return new Promise(resolve => {
        const options = {
            url: `https://m.aihoge.com/api${url}`,
            headers: {
                'Connection': 'keep-alive',
                'X-DEVICE-SIGN': 'xsb_hn',
                'X-CLIENT-VERSION': '1314',
                'accept': 'application/json, text/plain, */*',
                'user-agent': 'Mozilla/5.0 (Linux; Android 11; 21091116AC Build/RP1A.200720.011; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/94.0.4606.85 Mobile Safari/537.36;xsb_hn;xsb_hn;14.1.6;native_app;6.11.0',
                'HTTP-X-H5-VERSION': '1',
                'member': member,
                'X-DEVICE-ID': '000',
                'accountId': accountId,
                'x-requested-with': 'com.hoge.android.app.dachao',
                'sec-fetch-site': 'same-origin',
                'sec-fetch-mode': 'cors',
                'sec-fetch-dest': 'empty',
                'accept-language': 'zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7',
            },
            encoding: null
        };
        $.get(options, (err, resp, data) => {
            try {
                if (err) {
                    console.log(`请求失败: ${err}`);
                    resolve(null);
                } else {
                    const processedData = handleCompressedData(data);
                    if (processedData) {
                        resolve(JSON.parse(processedData));
                    } else {
                        resolve(null);
                    }
                }
            } catch (e) {
                console.log(`解析响应失败: ${e}`);
                resolve(null);
            }
        });
    });
}

// 活动POST请求
async function activityPost(url, body, sessionId, accountId) {
    return new Promise(resolve => {
        const options = {
            url: `https://m.aihoge.com/api${url}`,
            headers: {
                'Connection': 'keep-alive',
                'X-DEVICE-SIGN': 'xsb_hn',
                'X-CLIENT-VERSION': '1314',
                'Content-Type': 'application/json;charset=UTF-8',
                'accept': 'application/json, text/plain, */*',
                'user-agent': 'Mozilla/5.0 (Linux; Android 11; 21091116AC Build/RP1A.200720.011; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/94.0.4606.85 Mobile Safari/537.36;xsb_hn;xsb_hn;14.1.6;native_app;6.11.0',
                'HTTP-X-H5-VERSION': '1',
                'member': '',
                'sessionId': sessionId,
                'X-DEVICE-ID': '000',
                'accountId': accountId,
                'x-requested-with': 'com.hoge.android.app.dachao',
                'sec-fetch-site': 'same-origin',
                'sec-fetch-mode': 'cors',
                'sec-fetch-dest': 'empty',
                'accept-language': 'zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7',
            },
            body: JSON.stringify(body),
            encoding: null
        };
        $.post(options, (err, resp, data) => {
            try {
                if (err) {
                    console.log(`请求失败: ${err}`);
                    resolve(null);
                } else {
                    const processedData = handleCompressedData(data);
                    if (processedData) {
                        resolve(JSON.parse(processedData));
                    } else {
                        resolve(null);
                    }
                }
            } catch (e) {
                console.log(`解析响应失败: ${e}`);
                resolve(null);
            }
        });
    });
}

// 配置解析函数
function parseWechatBaseConfig() {
    if (!QYWX_BASE_CONFIG) {
        console.log("⚠️ 未设置企业微信基础配置");
        return false;
    }
    const parts = QYWX_BASE_CONFIG.split('#');
    if (parts.length < 4) {
        console.log("❌ 企业微信基础配置格式错误");
        return false;
    }
    corpId = parts[0].trim();
    secret = parts[1].trim();
    agentId = parts[2].trim();
    proxyUrl = parts[3].trim();
    console.log("✅ 企业微信基础配置解析成功");
    return true;
}

function parseReceiverConfig() {
    if (!DC_separate) {
        console.log("⚠️ 未设置个人通知接收人");
        return;
    }
    const lines = DC_separate.split('\n');
    for (const line of lines) {
        if (!line.trim()) continue;
        const parts = line.split('#');
        if (parts.length >= 3) {
            const receiverId = parts[0].trim();
            const phone = parts[1].trim();
            const remark = parts[2].trim();
            receiverConfig[phone] = { receiverId, remark };
            phoneRemarks[phone] = remark;
            console.log(`✅ 个人通知: ${receiverId} -> ${phone} (${remark})`);
        }
    }
}

// 修改汇总通知配置解析 - 只需要接收人ID和手机号列表
function parseSummaryReceiverConfig() {
    if (!DC_Summary) {
        console.log("⚠️ 未设置汇总接收人");
        return;
    }
    const lines = DC_Summary.split('\n');
    for (const line of lines) {
        if (!line.trim()) continue;
        const parts = line.split('|');
        if (parts.length >= 2) {
            const receiverId = parts[0].trim();
            const phones = parts[1].split('#').map(phone => phone.trim()).filter(phone => phone);
            
            if (receiverId && phones.length > 0) {
                summaryReceivers.push({ receiverId, phones });
                console.log(`✅ 汇总通知: ${receiverId} 有 ${phones.length} 个用户`);
            } else {
                console.log(`⚠️ 汇总接收人配置无效: ${line}`);
            }
        } else {
            console.log(`⚠️ 忽略无效的汇总通知配置行: ${line}`);
        }
    }
}

function getDisplayName(phone) {
    return phoneRemarks[phone] || phone;
}

function generateAccountMessage(redPackets) {
    if (!redPackets || redPackets.length === 0) return null;
    
    let message = "大潮重要通知：\n1. 请及时领取\n2. 链接有效期24小时\n";
    redPackets.forEach((packet, i) => {
        message += `3.${i + 1} 微信红包【${packet.content}】点击进入领取：${packet.link}\n`;
    });
    return message;
}

// 生成汇总通知消息 - 只包含指定手机号的账号
function generateSummaryMessage(phones) {
    // 过滤出指定手机号的账号结果
    const filteredResults = allResults.filter(account => phones.includes(account.phone));
    
    let totalAccounts = filteredResults.length;
    let accountsWithPackets = filteredResults.filter(a => a.redPackets.length > 0);
    let totalPackets = filteredResults.reduce((sum, a) => sum + a.redPackets.length, 0);
    let totalAmount = filteredResults.reduce((sum, a) => sum + a.totalAmount, 0).toFixed(2);
    
    let message = "💰 大潮红包汇总通知\n";
    message += `📊 账号总数: ${totalAccounts}\n`;
    message += `✅ 成功处理: ${accountsWithPackets.length}\n`;
    message += `🎁 红包总数: ${totalPackets}\n`;
    message += `💰 总金额: ${totalAmount}元\n`;
    
    if (totalPackets === 0) {
        message += "\n无可领取红包";
    } else {
        message += "\n详细结果:\n";
        accountsWithPackets.forEach((account, i) => {
            message += `${i + 1}. ${account.displayName}: ${account.message}\n`;
        });
    }
    
    return message;
}

async function sendNotifications() {
    if (!corpId || !secret || !agentId || !proxyUrl) {
        console.log("❌ 企业微信配置不完整，跳过通知发送");
        return;
    }
    
    let accessToken = await getWechatAccessToken();
    if (!accessToken) {
        console.log("❌ 无法获取Access Token，通知发送失败");
        return;
    }
    
    // 发送个人通知（仅当有红包时）
    let notificationsSent = 0;
    for (const account of allResults) {
        if (!receiverConfig[account.phone]) {
            const displayName = getDisplayName(account.phone);
            console.log(`⚠️ 用户 ${displayName} 未配置个人接收人，跳过通知`);
            continue;
        }
        const message = generateAccountMessage(account.redPackets);
        if (!message) { // 没有红包时跳过
            console.log(`ℹ️ 用户 ${account.displayName} 没有红包，跳过个人通知`);
            continue;
        }
        const { receiverId, remark } = receiverConfig[account.phone];
        console.log(`📤 发送通知给 ${remark} (${receiverId})...`);
        const success = await sendWechatNotification(accessToken, receiverId, message);
        if (success) {
            console.log(`✅ ${remark} 通知发送成功`);
            notificationsSent++;
        } else {
            console.log(`❌ ${remark} 通知发送失败`);
        }
    }
    
    // 发送汇总通知（只发送给指定手机号的汇总）
    let summarySent = 0;
    for (const receiver of summaryReceivers) {
        const { receiverId, phones } = receiver;
        const message = generateSummaryMessage(phones);
        console.log(`📤 发送汇总通知给 ${receiverId}...`);
        const success = await sendWechatNotification(accessToken, receiverId, message);
        if (success) {
            console.log(`✅ 汇总通知发送成功`);
            summarySent++;
        } else {
            console.log(`❌ 汇总通知发送失败`);
        }
    }
    
    console.log(`\n🎉 完成! 发送 ${notificationsSent} 条个人通知, ${summarySent} 条汇总通知`);
}

async function getWechatAccessToken() {
    const url = `${proxyUrl}/cgi-bin/gettoken?corpid=${corpId}&corpsecret=${secret}`;
    return new Promise((resolve) => {
        $.get({url}, (err, resp, data) => {
            try {
                if (err) {
                    console.log(`❌ 获取Access Token失败: ${err}`);
                    resolve(null);
                } else {
                    const result = JSON.parse(data);
                    if (result.errcode === 0) {
                        console.log("✅ 获取Access Token成功");
                        resolve(result.access_token);
                    } else {
                        console.log(`❌ 获取Access Token失败: ${result.errmsg}`);
                        resolve(null);
                    }
                }
            } catch (e) {
                console.log(`❌ 解析Access Token响应失败: ${e}`);
                resolve(null);
            }
        });
    });
}

async function sendWechatNotification(accessToken, receiverId, message) {
    if (!receiverId || !message) return false;
    
    const url = `${proxyUrl}/cgi-bin/message/send?access_token=${accessToken}`;
    const payload = {
        "touser": receiverId,
        "msgtype": "text",
        "agentid": agentId,
        "text": {"content": message},
        "safe": 0
    };
    
    return new Promise((resolve) => {
        $.post({
            url: url,
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(payload)
        }, (err, resp, data) => {
            try {
                if (err) {
                    console.log(`❌ 发送通知失败: ${err}`);
                    resolve(false);
                } else {
                    const result = JSON.parse(data);
                    resolve(result.errcode === 0);
                }
            } catch (e) {
                console.log(`❌ 解析通知响应失败: ${e}`);
                resolve(false);
            }
        });
    });
}

// 稳定可靠的Env类
function Env(name, opts) {
    return new class {
        constructor(name, opts) {
            this.name = name;
            this.data = {};
            this.logs = [];
            this.startTime = Date.now();
            Object.assign(this, opts);
            console.log(`🔔${this.name}, 开始!`);
        }
        isNode() { return typeof module !== 'undefined' && module.exports; }
        getdata(key) { return this.data[key] || null; }
        setdata(val, key) { this.data[key] = val; return true; }
        log(...t) { 
            this.logs.push(...t); 
            console.log(t.join(' '));
        }
        wait(t) { return new Promise(e => setTimeout(e, t)); }
        get(opts, callback = () => {}) {
            const request = require('request');
            request.get(opts, (err, resp, body) => {
                callback(err, resp, body);
            });
        }
        post(opts, callback = () => {}) {
            const request = require('request');
            request.post(opts, (err, resp, body) => {
                callback(err, resp, body);
            });
        }
        done() { 
            const costTime = ((Date.now() - this.startTime) / 1000).toFixed(2);
            console.log(`🔔${this.name}, 结束! 🕛 ${costTime} 秒`);
        }
    }(name, opts);
}